package com.usian.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.admin.mapper.AdUserMapper;
import com.usian.admin.service.AdUserService;
import com.usian.model.admin.dtos.AdUserDto;
import com.usian.model.admin.pojos.AdUser;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.utils.common.AppJwtUtil;
import com.usian.utils.common.BCrypt;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;

/**
 * ClassName: AdUserServiceImpl
 * Author:   WGG
 * Date:    2022-11-2022/11/11-11:54
 * Version: 1.0
 * Description:
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {


    @Override
    public ResponseResult login(AdUserDto adUserDto) {
        //判断用户名及密码是否为空
        if (adUserDto.getName()==null || adUserDto.getPassword()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //根据用户名查询，判断用户是否存在
        Wrapper wrapper = new QueryWrapper<>();
        ((QueryWrapper)wrapper).eq("name", adUserDto.getName());
        AdUser adUser = getOne(wrapper);
        if (adUser!=null){
            //校验密码是否正确
            String password = DigestUtils.md5DigestAsHex((adUserDto.getPassword() + adUser.getSalt()).getBytes());
            if (password.equals(adUser.getPassword())){
                //响应结果(token，用户信息)
                HashMap<String, Object> map = new HashMap<>();
                adUser.setPassword("");
                adUser.setSalt("");
                map.put("token", AppJwtUtil.getToken(adUser.getId().longValue()));
                map.put("user",adUser);
                return ResponseResult.okResult(map);
            }else {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
    }

//    public static void main(String[] args) {
//        Integer a = 123456;
//        String password = DigestUtils.md5DigestAsHex((a+"123abc").getBytes());
//        System.out.println(password);
//    }
}
